#include "bsp_adc.h"
#include <math.h>

ADCdata_t ADCdata;

void BSP_ADC_Init(void)
{
    // 开启ADC自校准
    HAL_ADCEx_Calibration_Start(&hadc1, ADC_SINGLE_ENDED);
    HAL_ADCEx_Calibration_Start(&hadc2, ADC_SINGLE_ENDED);

    // 启动DMA搬运ADC规则组数据
    HAL_ADC_Start_DMA(&hadc1, (uint32_t*)ADCdata.ADC1data.ADC1_Value, 3);
    HAL_ADC_Start_DMA(&hadc2, (uint32_t*)ADCdata.ADC2data.ADC2_Value, 6);

    // 需要先开启ADC注入组中断，再启动ADC1注入组转换
    HAL_ADCEx_InjectedStart_IT(&hadc1);
    HAL_ADCEx_InjectedStart(&hadc1);

    // 关闭DMA传输完成中断
    HAL_NVIC_DisableIRQ(DMA1_Channel1_IRQn);
    HAL_NVIC_DisableIRQ(DMA1_Channel2_IRQn);
}

ADC1data_t BSP_ADC1_Read(void)
{
    ADC1data_t ADC1data_tmp = ADCdata.ADC1data;
    ADC1data_tmp.ADC1_Channel.IBUS_f =
        (((float)ADC1data_tmp.ADC1_Channel.IBUS - 2048) * (3.3f / 4095.0f)) / (0.001f * 20.0f);

    float Temp1;      // 温度值
    float R = 10000;  // 热敏电阻NTC103
    float B = 3428;   // NTC固有参数
    float T2 = (273.15f + 25.0f);

    float V_NTC1 = (float)ADC1data_tmp.ADC1_Channel.NTC1 * (3.3f / 4095.0f);  // 测得实际电压值
    float Rt1 = V_NTC1 * 10000.0f / (3.3f - V_NTC1);                          // 推测得到的电阻值
    Temp1 = 1.0f / (logf(Rt1 / R) / B + 1 / T2);                              // 温度计算
    ADC1data_tmp.ADC1_Channel.NTC1_f = Temp1 - 273.15f;                       // 最终的温度值

    ADC1data_tmp.ADC1_Channel.NTC3_f = (float)ADC1data_tmp.ADC1_Channel.NTC3 - 2048.0f;

    return ADC1data_tmp;
}

ADC2data_t BSP_ADC2_Read(void)
{
    ADC2data_t ADC2data_tmp = ADCdata.ADC2data;
    ADC2data_tmp.ADC2_Channel.VBUS_f = (float)ADC2data_tmp.ADC2_Channel.VBUS * (3.3f / 4095.0f) * 16.0f;
    ADC2data_tmp.ADC2_Channel.VA_f = (float)ADC2data_tmp.ADC2_Channel.VA * (3.3f / 4095.0f) * 16.0f;
    ADC2data_tmp.ADC2_Channel.VB_f = (float)ADC2data_tmp.ADC2_Channel.VB * (3.3f / 4095.0f) * 16.0f;
    ADC2data_tmp.ADC2_Channel.VC_f = (float)ADC2data_tmp.ADC2_Channel.VC * (3.3f / 4095.0f) * 16.0f;

    float Temp2;      // 温度值
    float R = 10000;  // 热敏电阻NTC103
    float B = 3428;   // NTC固有参数
    float T2 = (273.15f + 25.0f);

    float V_NTC2 = (float)ADC2data_tmp.ADC2_Channel.NTC2 * (3.3f / 4095.0f);  // 测得实际电压值
    float Rt2 = V_NTC2 * 10000.0f / (3.3f - V_NTC2);                          // 推测得到的电阻值
    Temp2 = 1.0f / (logf(Rt2 / R) / B + 1 / T2);                              // 温度计算
    ADC2data_tmp.ADC2_Channel.NTC2_f = Temp2 - 273.15f;                       // 最终的温度值

    return ADC2data_tmp;
}

__weak void USER_ADC_Injected_Callback() {}

void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef* hadc)
{
    USER_ADC_Injected_Callback();
}
